package com.muh.rabbitmq;

import com.rabbitmq.client.*;

import java.util.HashMap;
import java.util.Map;

public class FirstProducer {
    private static final String HOST_NAME = "39.104.74.101";
    private static final int PORT = 5672;
    private static final String QUEUE_NAME = "test3";//队列名称
    private static final String USER_NAME = "admin";
    private static final String PASSWORD = "admin";
    private static final String VIRTUAL_HOST = "/mirror";//虚拟机

    private static final String EXCHANGE_NAME = "callbackExchange";//交换机


    public static void main(String[] args) throws Exception {
        //建立连接Factory
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST_NAME);
        factory.setPort(PORT);
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        factory.setVirtualHost(VIRTUAL_HOST);

        //建立连接
        Connection connection = factory.newConnection();
        //创建一个通道用来传输数据
        Channel channel = connection.createChannel();
        //声明交换机
        Map<String, Object> exchangeDeclareParams = new HashMap<String, Object>();
//        exchangeDeclareParams.put("alternate-exchange", “asdf”);
        /**
         * 1、创建一个交换机，如果服务器已经有了相同名称的交换机，则交换机的类型还有其他资格字段必须和服务器一致，否则会报错
         * exchangeName交换机的名称
         * type 交换机的类型 枚举BuiltinExchangeType
         * durable 是否持久化
         * autoDelete 是否自动删除
         * 构建其他参数
         */
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT, true, false, exchangeDeclareParams);

        /**
         * 2、申明一个对列，队列名，durable是否持久化，exclusive是否独占，autodelete是否自动删除消息
         * exclusive是否独占，如果为true这个对列只允许当前这个Connection使用，如果再开一个Connection取使用相同名称的对列queue是不允许的
         * 这几个参数跟创建对列的页面是一致的
         * 如果broker上没有对列，那么就会自动创捷对列
         * 但是如果broker上已经有了这个对列，那么对列的属性必须匹配，否则会报错
         */
        Map<String, Object> queueDeclareParams = new HashMap<String, Object>();
        //可以看到申明对列的时候无法指定对列的类型
        queueDeclareParams.put("x-queue-type", "stream");//通过x-queuq-type来指定对列的类型
        queueDeclareParams.put("x-max-length-bytes", 20000000000L);
        queueDeclareParams.put("x-stream-max-segment-size-bytes", 100000000);
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);

        //3、绑定exchange和queue
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "key1");

        //4、发送消息
        String message1 = "Hello World，我是消息生产者1";
        channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message1.getBytes());

        //发送消息
        String message2 = "Hello World，我是消息生产者2";
        channel.basicPublish(EXCHANGE_NAME, "key1", MessageProperties.PERSISTENT_TEXT_PLAIN, message2.getBytes());

        channel.close();
        connection.close();
    }
}
